package com.alan.boot.mongo.controller;

import com.alan.boot.mongo.dao.BinaryDataRepository;
import com.alan.boot.mongo.dao.PersonRepository;
import com.alan.boot.mongo.entity.BinaryData;
import com.alan.boot.mongo.entity.Location;
import com.alan.boot.mongo.entity.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@RestController
public class DataController {
    @Resource
    PersonRepository personRepository;
    @Resource
    BinaryDataRepository binaryDataRepository;

    @RequestMapping("/save")
    public Person save(){
        Person p = new Person("caocao",32);
        Collection<Location> locations =  new LinkedHashSet<Location>();
        Location loc1 = new Location("上海","2009");
        Location loc2 = new Location("合肥","2010");
        Location loc3 = new Location("广州","2011");
        Location loc4 = new Location("马鞍山","2012");
        locations.add(loc1);
        locations.add(loc2);
        locations.add(loc3);
        locations.add(loc4);
        p.setLocations(locations);

        return personRepository.save(p);
    }

    @RequestMapping("/getByName")
    public Person getByName(String name){
        return personRepository.findByName(name);
    }

    @RequestMapping("/findByAge")
    public List<Person> findByAge(Integer age){
        return personRepository.findByAge(age);
    }

    @RequestMapping("/listByAge")
    public List<Person> listByAge(Integer age){
        return personRepository.withQueryFindByAge(age);
    }


    @PostMapping("/saveBinary")
    public String saveBinary() {
        BinaryData data = new BinaryData();
        data.setId("testID");
        data.setData("这是一段Java代码".getBytes(StandardCharsets.UTF_8));
        data.setCreateTime(new Date());
        binaryDataRepository.save(data);
        return "OK";
    }

    @GetMapping("/getBinary")
    public String getBinary() {
        Optional<BinaryData> testID = binaryDataRepository.findById("testID");
        if (testID.isPresent()) {
            BinaryData binaryData = testID.get();
            return new String(binaryData.getData(), StandardCharsets.UTF_8);
        }
        return "NOT FOUND";
    }
}
